package wanba.wanbatv.com.wudao.activity;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ProgressBar;
import android.widget.Toast;

import com.android.volley.AuthFailureError;
import com.android.volley.DefaultRetryPolicy;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.json.JSONTokener;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;

import wanba.wanbatv.com.wudao.R;
import wanba.wanbatv.com.wudao.util.AppUtil;
import wanba.wanbatv.com.wudao.util.Crypto;
import wanba.wanbatv.com.wudao.util.Util;
import wanba.wanbatv.com.wudao.utils.Product;

public class PayWudaoActivity extends Activity {
    private WebView webView;
    String orderInfo=null;
    JSONArray arr_zhifubao=null;
    ProgressBar pro_pay;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_pay);
        pro_pay=(ProgressBar)findViewById(R.id.pro_pay);
        webView=(WebView)findViewById(R.id.webview);
        webView.setBackgroundColor(0);
        webView.setFocusable(true);
        webView.setFocusableInTouchMode(true);
        webView.requestFocus();
        webView.requestFocusFromTouch();
        WebSettings webSettings=webView.getSettings();
        webSettings.setJavaScriptEnabled(true);
//        webSettings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.NARROW_COLUMNS);
//        webSettings.setUseWideViewPort(true);
//        webSettings.setLoadWithOverviewMode(true);
        webSettings.setDefaultTextEncodingName("UTF-8");
        webView.setOnKeyListener(new View.OnKeyListener() {
            @Override
            public boolean onKey(View v, int keyCode, KeyEvent event) {
                if (event.getAction() == KeyEvent.ACTION_DOWN) {
                    if (event.getKeyCode() == KeyEvent.KEYCODE_BACK) {
                        finish();
                    } else {
                        Log.d("order_page", "@@@ onkey " + event.getKeyCode());
                        webView.loadUrl("javascript:orderKeyHandle(" + keyCode + ")");
                    }
                    return true;
                }
                return false;
            }
        });

        webView.setWebViewClient(new MyWebViewClient());


        chanpinbao();
        Toast.makeText(PayWudaoActivity.this,"正在加载付款页面，请稍候。",Toast.LENGTH_SHORT).show();


//        webView.loadUrl("http://baidu.com");
//        webView.setWebViewClient(new WebViewClient(){
//            @Override
//            public boolean shouldOverrideUrlLoading(WebView view, String url) {
//                view.loadUrl(url);
//                return true;
//            }
//        });
    }



    //    @Override
//    public boolean onKeyDown(final int keyCode,final KeyEvent event) {
//        runOnUiThread(new Runnable() {
//            @Override
//            public void run() {
//
//                webView.loadUrl("javascript:orderKeyHandle("+keyCode+")");
//                Log.e("javascript",keyCode+"");
//            }
//        });
//        return super.onKeyDown(keyCode, event);
//    }

    private  void dingdanhao(){
        Log.e("dingdanhao join","ok");
        try {
            JSONObject obj = arr_zhifubao.getJSONObject(0);

        final   String subject=obj.getString("subject");
        final   String subjectid=obj.getString("subjectId");
        final   String price=obj.getString("price");
        RequestQueue requestQueue = Volley.newRequestQueue(PayWudaoActivity.this);
        String url="http://121.201.7.173:8063/proxy/61.191.46.214/8087/postapi/common/wpay/getorder";
        StringRequest stringRequest = new StringRequest(com.android.volley.Request.Method.POST,url,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        Log.e("response",response+"");
                        JSONObject obj_zhifubao= null;
                        try {
                            obj_zhifubao = (JSONObject) new JSONTokener(response).nextValue();
                            JSONObject oobj=obj_zhifubao.getJSONObject("data");
                            String order=oobj.getString("order");
                            orderInfo="orderId="+order+"|itvAccount="+ AppUtil.STB.UserID+"|productId=zg_wanba"+"|price=1500";
                            orderInfo=jiami(orderInfo);
                            aaa();
                            pro_pay.setVisibility(View.GONE);
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }

                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                Toast.makeText(PayWudaoActivity.this,"请求订单号超时，请检查网络并返回重试。",Toast.LENGTH_SHORT).show();
                error.printStackTrace();
            }
        }) {
            @Override
            public Map<String, String> getHeaders() throws AuthFailureError {
                HashMap<String, String> headers = new HashMap<String, String>();
                PackageInfo pi= null;
                try {
                    pi = PayWudaoActivity.this.getPackageManager().getPackageInfo(PayWudaoActivity.this.getPackageName(), 0);
                    headers.put("accept", "applicationnd.wanba.wanbatv.com.wudao;version="+pi.versionName);
                    headers.put("app_version", pi.versionName);
                    headers.put("app_package_name",pi.packageName);
                } catch (PackageManager.NameNotFoundException e) {
                    e.printStackTrace();
                }


                // MyLog.d(TAG, "headers=" + headers);
                return headers;
            }
            @Override
            public String getBodyContentType() {
                return "application/x-www-form-urlencoded; charset=" + getParamsEncoding();
            }
            @Override
            protected Map<String, String> getParams() {
                //在这里设置需要post的参数
                HashMap<String, String> params = new HashMap<String, String>();
                params.put("partner","");
                params.put("subject", subject);
                params.put("subjectid",subjectid);
                params.put("price",price);
                params.put("provider","ahpay");
                params.put("stb", Util.getDeviceId(PayWudaoActivity.this));
                params.put("flavor", Product.flavor);

                return params;
            }
        };
            stringRequest.setRetryPolicy(new DefaultRetryPolicy(30000,3,1.0f));
        requestQueue.add(stringRequest);
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }
    private void chanpinbao(){
        Log.d("ricardo==","chanpin");
        RequestQueue rq_2 = Volley.newRequestQueue(PayWudaoActivity.this.getApplicationContext());
        final JsonObjectRequest request_2 = new JsonObjectRequest("http://121.201.7.173:8063/proxy/61.191.46.214/8087/getapi/common/subjects/31259d2c48bec6a1ba589360c748e132?flavor="+ Product.flavor, null,
                new Response.Listener<JSONObject>() {

                    @Override
                    public void onResponse(JSONObject jsonObject) {
                        try {
                            Log.e("chaopinbao obj",jsonObject.toString());
                            JSONObject obj=jsonObject.getJSONObject("data");
                            JSONArray arr=obj.getJSONArray("list");
                            arr_zhifubao=arr;
                             dingdanhao();
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {
                Toast.makeText(PayWudaoActivity.this,"请求产品包超时，请检查网络并返回重试。",Toast.LENGTH_SHORT).show();
                volleyError.printStackTrace();
            }
        }

        ) {
            @Override
            public Map<String, String> getHeaders() throws AuthFailureError {
                HashMap<String, String> headers = new HashMap<String, String>();
                PackageInfo pi= null;
                try {
                    pi = PayWudaoActivity.this.getPackageManager().getPackageInfo(PayWudaoActivity.this.getPackageName(), 0);
                    headers.put("accept", "applicationnd.wanba.wanbatv.com.wudao;version="+pi.versionName);
                    headers.put("app_version", pi.versionName);
                    headers.put("app_package_name",pi.packageName);
                } catch (PackageManager.NameNotFoundException e) {
                    e.printStackTrace();
                }


                // MyLog.d(TAG, "headers=" + headers);
                return headers;
            }
        };
        request_2.setRetryPolicy(new DefaultRetryPolicy(30000,3,1.0f));

        rq_2.add(request_2);
    }
    private  String jiami(String orderInfo){
//        String msg = "使用3DES对数据进行加密";
//        byte[] secretArr = DES3Utils.encryptMode(msg.getBytes());
//        String jiami=Base64.encodeToString(secretArr,Base64.DEFAULT);
//        String res = null;
//        try {
//            res = new String(DES3Utils.decryptMode(Base64.decode(jiami, Base64.DEFAULT)), "utf-8");
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//        Log.e("jiami","3des result " + msg.equals(res) + " res " + res + ", encrypt " + jiami);

        String jiami= Crypto.TripleDES.encrypt(orderInfo,"26f545c0d092463185acdd3e2c73fdda");
//        String jiemi=Crypto.TripleDES.decrypt(jiami,"36161889369a412b923af17dafb0fe88");
        Log.e("jiami",jiami);
//        Log.e("jiemi",jiemi);
        return jiami;
    }
    @SuppressLint("LongLogTag")
    private void aaa(){
        Log.e("aaa join","ok");
//        RequestQueue requestQueue = Volley.newRequestQueue(PayWudaoActivity.this);
//        String url="http://61.191.45.116:7002/itv-api/order";
//        StringRequest stringRequest = new StringRequest(com.android.volley.Request.Method.POST,url,
//                new Response.Listener<String>() {
//                    @Override
//                    public void onResponse(String response) {
//
//                            Log.e("@@@@",response);
//
//                        webView.loadDataWithBaseURL("http://61.191.45.116:7002/itv-api/", response, "text/html", "UTF-8", null);
//                    }
//                }, new Response.ErrorListener() {
//            @Override
//            public void onErrorResponse(VolleyError error) {
//                error.printStackTrace();
//            }
//        }) {
//
//            @Override
//            public String getBodyContentType() {
//                return "application/x-www-form-urlencoded";
//            }
//            @Override
//            protected Map<String, String> getParams() {
//                //在这里设置需要post的参数
//                Map<String, String> map = new HashMap<String, String>();
//                map.put("providerId","shzg");
//                map.put("orderInfo",orderInfo);
//                map.put("returnUrl","http://121.201.7.173:8087/api/common/wpay/result/ahpay/"+AppUtil.STB.UserID);
//                map.put("notifyUrl","http://121.201.7.173:8087/api/common/wpay/paynotify/ahpay/"+AppUtil.STB.UserID);
//                map.put("userGroup",AppUtil.STB.UserGroup);
//                map.put("ip",AppUtil.STB.IP);
//                map.put("mac",AppUtil.STB.Mac);
//                map.put("userAgent","wanba");
//                map.put("deviceModel",AppUtil.STB.Model);
//                map.put("deviceSerialNo",AppUtil.STB.Sn);
//                map.put("deviceType","hd");
//
//
//                return map;
//            }
//        };
//        requestQueue.add(stringRequest);
//

        String url = "http://61.191.45.118:7002/itv-api/order";
        String postDate = null;
        try {
            postDate = "providerId=shzg&orderInfo="+ URLEncoder.encode(orderInfo,"utf-8")+"&returnUrl=http://61.191.46.214:8087/getapi/common/wpay/result/ahpay/"+ AppUtil.STB.UserID+"&notifyUrl=http://61.191.46.214:8087/postapi/common/wpay/paynotify/ahpay/"+AppUtil.STB.UserID+
                    "&userGroup="+AppUtil.STB.UserGroup+"&ip="+AppUtil.STB.IP+"&mac="+AppUtil.STB.Mac+"&userAgent=wanba&deviceModel="+AppUtil.STB.Model+"&deviceSerialNo="+AppUtil.STB.Sn+"&deviceType=hd";
            webView.postUrl(url, postDate.getBytes());
        } catch (UnsupportedEncodingException e) {
            Log.e("UnsupportedEncodingException",e.getMessage()+"");
            e.printStackTrace();
        }


    }

    private class MyWebViewClient extends WebViewClient {

        @Override
        public void onPageStarted(WebView view, String url, Bitmap favicon) {
            super.onPageStarted(view, url, favicon);
        }

        @Override
        public boolean shouldOverrideKeyEvent(WebView view, KeyEvent event) {
            return true;
        }

        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            Log.e("@@@ return:",url);
           if(url.startsWith("http://121.201.7.173:8063/proxy/61.191.46.214/8087")){
               RequestQueue rq = Volley.newRequestQueue(PayWudaoActivity.this.getApplicationContext());
               JsonObjectRequest request = new JsonObjectRequest(url, null,
                       new Response.Listener<JSONObject>() {

                           @Override
                           public void onResponse(JSONObject jsonObject) {
                               try {
                                   Log.e("fanhui",jsonObject+"");
                                   JSONObject obj=jsonObject.getJSONObject("data");
                                   String orderReturn=obj.getString("orderReturn");

                                   if(orderReturn.equals("cancel")){
                                       finish();
                                   }
                                   if(orderReturn.equals("fail")){
                                       Toast.makeText(PayWudaoActivity.this,"操作错误",Toast.LENGTH_SHORT).show();
                                       finish();
                                   }
                                   if(orderReturn.equals("success")){
                                       Toast.makeText(PayWudaoActivity.this,"购买成功",Toast.LENGTH_SHORT).show();

                                       if(BengbengtiaoChannelActivity.mitem!=null){
                                           BengbengtiaoChannelActivity.xuanze=true;
                                       }
                                       if(DupiwuChannelActivity.mitem!=null){
                                           DupiwuChannelActivity.xuanze=true;
                                       }
                                       if(JiewuChannelActivity.mitem!=null){
                                           JiewuChannelActivity.xuanze=true;
                                       }
                                       if(WangguangchengChannelActivity.mitem!=null){
                                           WangguangchengChannelActivity.xuanze=true;
                                       }
                                       LoginWudaoActivity.is_dinggou=true;
                                       finish();
                                   }
                               } catch (JSONException e) {
                                   e.printStackTrace();
                               }
                           }
                       }, new Response.ErrorListener() {
                   @Override
                   public void onErrorResponse(VolleyError volleyError) {
                       Log.e("return"," error");
                       volleyError.printStackTrace();
                   }
               }

               );
               request.setRetryPolicy(new DefaultRetryPolicy(60000,3,1.0f));
               rq.add(request);
           }else{
               webView.loadUrl(url);
           }
            return true;
        }

        @Override
        public void onPageFinished(WebView view, String url) {
            super.onPageFinished(view, url);
        }
    }
}
